package com.gzhryc.shared_device.oem.code.user.services;

import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.oem.code.user.dao.UserAddressDao;
import com.gzhryc.shared_device.oem.code.user.dao.db.UserAddress;
import com.gzhryc.shared_device.oem.code.user.dao.enums.UserAddressEnum;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class UserAddressService {

    static Logger log = Logger.getLogger(UserAddressService.class);

    public static UserAddressService self() {
        return MultiDBTools.getService(UserAddressService.class, true);
    }

    public static UserAddressService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, UserAddressService.class, true);
    }

    UserAddressDao dao;

    public UserAddressService(String jdbcKey) {
        this.dao = new UserAddressDao(jdbcKey);
    }

    public List<UserAddress> findByUserId(Long userId){
        if(userId != null){
            Conditions conditions = new Conditions(UserAddress.class);
            conditions.and().is("userId",userId);

            try {
                return dao.findByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public Long countByUserId(Long userId){
        if(userId != null){
            Conditions conditions = new Conditions(UserAddress.class);
            conditions.and().is("userId",userId);

            try {
                return dao.count(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return 0L;
    }

    public UserAddress getDefByUserId(Long userId) {
        if(userId != null) {
            Conditions condition = new Conditions(UserAddress.class);
            condition.and().is("userId", userId);
            condition.and().is("state", UserAddressEnum.State.Default.index());
            try {
                return dao.get(condition);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public UserAddress getByIdAndUserId(Long id,Long userId) {
        if(id != null && userId != null) {
            Conditions condition = new Conditions(UserAddress.class);
            condition.and().is("id", id);
            condition.and().is("userId", userId);

            try {
                return dao.get(condition);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public boolean add(UserAddress mailAddress) throws LogicException {
        if(mailAddress != null) {
            mailAddress.setCreateDate(new Date());
            mailAddress.setState(UserAddressEnum.State.Normal.index());

            Long total = this.countByUserId(mailAddress.getUserId());
            if(total >= 10){
                throw new LogicException("已添加了10个收件地址");
            }
            if(total <= 0) {
                mailAddress.setState(UserAddressEnum.State.Default.index());
            }
            try {
                return dao.insert(mailAddress) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }

    public boolean updateNotNull(UserAddress mailAddress) throws LogicException {
        if(mailAddress != null && mailAddress.getId() != null) {
            //检查默认地址
            Long oldDefMemberAddressId = null;
            if(UserAddressEnum.State.Default.index().equals(mailAddress.getState())){
                UserAddress defMemberAddress = getDefByUserId(mailAddress.getUserId());
                if(defMemberAddress != null && !defMemberAddress.getId().equals(mailAddress.getId())){
                    oldDefMemberAddressId = defMemberAddress.getId();
                }
            }else {
                UserAddress defMemberAddress = getDefByUserId(mailAddress.getUserId());
                if(defMemberAddress != null && defMemberAddress.getId().equals(mailAddress.getId())){
                    throw new LogicException("必须设置一个默认地址");
                }
            }
            JdbcSession.begin();
            try {
                if(dao.updateNotNull(mailAddress) > 0){
                    if(oldDefMemberAddressId != null){
                        UserAddress updateEntity = new UserAddress();
                        updateEntity.setId(oldDefMemberAddressId);
                        updateEntity.setState(UserAddressEnum.State.Normal.index());
                        if(dao.updateNotNull(updateEntity) > 0){
                            JdbcSession.commit();
                            return true;
                        }
                    }else{
                        JdbcSession.commit();
                        return true;
                    }
                }
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            } finally{
                JdbcSession.end();
            }
        }
        return false;
    }

    public boolean toDef(Long id,Long userId) throws LogicException {
        UserAddress mailAddress = getByIdAndUserId(id,userId);
        if(mailAddress == null){
            throw new LogicException("未找到收货地址");
        }
        if(UserAddressEnum.State.Default.index().equals(mailAddress.getState())){
            return true;
        }

        Conditions condition = new Conditions(UserAddress.class);
        condition.and().is("userId", userId);

        UserAddress updateEntity = new UserAddress();
        updateEntity.setState(UserAddressEnum.State.Normal.index());

        JdbcSession.begin();
        try {
            if(dao.updateNotNull(updateEntity,condition) > 0){
                condition.and().is("id",id);
                updateEntity.setState(UserAddressEnum.State.Default.index());
                if(dao.updateNotNull(updateEntity,condition) > 0){
                    JdbcSession.commit();
                    return true;
                }
            }
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        } finally{
            JdbcSession.end();
        }
        return false;
    }

}
